var topicModel=require('../models/topic')
var _=require('lodash')
var eventproxy=require('eventproxy')
var common=require('../common/function')
exports.index=(req,res)=>{
	var page=parseInt(req.query.page)||1
	page=page>0?page:1
	var tab=req.query.tab||'tab1'
	var query={}
	if(tab!='tab1'){
		query.tab=tab
	}
	var ep=new eventproxy()
	ep.all('topic_data_ok','page_count_ok',(topics,pageCount)=>{
		res.render('index',{topics:topics,tab:tab,page:page,pageCount:pageCount})
	})
	var count=3
	var option={skip:(page-1)*count,limit:count,sort:'-insertTime'}
	topicModel.getTopics(query,option,(err,topics)=>{
		topics=_.map(topics,(topic)=>{
			topic.timeStr=common.formatTime(topic.insertTime)
			return topic
		})
		ep.emit('topic_data_ok',topics)

	})
	topicModel.count(query,(er,allCount)=>{
		var pageCount=Math.ceil(allCount/count)
		ep.emit('page_count_ok',pageCount)
	})
}